# -*- py-indent-offset: 4 -*- 
# -*- tab-width: 8 -*- 
# -*- indent-tabs-mode: nil -*-
 
from etgui import *
import CmdNo,string,sys
from PageLayout import *
class RunPython:
	def __init__(self,model,outfield):
		self.model=model
		self.outfield=outfield
		self.data=''
		self.context={}
	def Exec(self):
		cmd=self.model.GetValue("Input")
		stdout=sys.stdout
		stderr=sys.stderr
		sys.stdout=self
		sys.stderr=self
		try:
			try:
				try:
					exec '_=' + cmd in self.context,self.context
					if self.context['_'] is not None:
						print self.context['_']
				except:
					exec cmd in self.context,self.context
			except:
				print sys.exc_type,sys.exc_value
		finally:
			sys.stdout=stdout
			sys.stderr=stderr
	def write(self,data):
		self.data=self.data+data
		if '\n' in data:
			self.outfield.SetString(self.data)
			#self.data=''

def MakeDialog():
	model=PotGuiModel()
	outfield=MultilineTextItem("",-1,gFixedFont)
	evaluator=RunPython(model,outfield)
	panel=VSplitExpander(
		align=eVObjHExpand|eVObjVExpand,
		items=[
			PotGuiTextField("Input",MultiLineField(-1,10,500)),
			VSplitter(
				items=[
					Scroller(outfield)
				]
			)
		]
	)
 
	dialog=PotGuiDialog(
		model,
		MakeDialogWithButtons(
			panel,
			ActionButton("Exec",default=1,action=evaluator.Exec),
			ActionButton(CmdNo.cIdCancel,"Close"),
		),
		"Pot GUI",
		eWinDefault
	)
	return dialog
gDialog=None
def Show():
	global gDialog
	if not gDialog:
		gDialog=MakeDialog()
	gDialog.ShowUnderMouse()
